using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//当一个物体B在物体A左前方20度角或右前方30度范围内，并且离A只有5米距离时，在控制台打印“发现入侵者”
public class Lesson3_exercise2 : MonoBehaviour
{
    public Transform Player;
    public Transform Monster;

    public float atkDistance = 5;
    public float leftAngle = 20;
    public float rightAngle = 30;

    void DrawAtkArea()
    {
        //绘制攻击区域
        Vector3 center = Monster.position;
        Vector3 forward = Monster.forward;
        // 绘制扇形的两条边
        Debug.DrawRay(center, forward * atkDistance, Color.red);
        Debug.DrawRay(center, Quaternion.Euler(0, rightAngle / 2, 0) * forward * atkDistance, Color.red);
        Debug.DrawRay(center, Quaternion.Euler(0, -leftAngle / 2, 0) * forward * atkDistance, Color.red);
        // 绘制扇形弧线（可选，增强可视化）
        for (float angle = -leftAngle / 2; angle <= rightAngle / 2; angle += 5f)
        {
            Vector3 dir = Quaternion.Euler(0, angle, 0) * forward;
            Debug.DrawRay(center, dir * atkDistance, Color.yellow);
        }
    }

    void Update()
    {
        DrawAtkArea();
        Debug.DrawRay(Monster.position, Monster.forward, Color.red);
        Debug.DrawRay(Monster.position, Player.position - Monster.position, Color.red);

        float distance = Vector3.Distance(Monster.position, Player.position);
        if (distance <= atkDistance)
        {
            //判断左右
            Vector3 relativeDir = Player.position - Monster.position;
            Vector3 cross = Vector3.Cross(Monster.forward, relativeDir);
            //判断前后
            if (Vector3.Dot(Monster.forward, relativeDir) > 0)
            {
                float angle = Vector3.Angle(Monster.forward, relativeDir);
                if (cross.y >= 0 && angle <= rightAngle/2)
                {
                    Debug.LogFormat("右前方发现入侵者");
                }
                else if(cross.y < 0 && angle <= leftAngle/2)
                {
                    Debug.LogFormat("左前方发现入侵者");
                }
            }
        }
    }
}
